package com.boot.springboot.component.springwebsocket.controller;

import com.alibaba.fastjson.JSONObject;
import com.boot.springboot.aop.MyAutoLogInterceptor;
import com.boot.springboot.component.springwebsocket.domain.MsgWeixin;
import com.github.houbb.auto.log.annotation.AutoLog;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.messaging.handler.annotation.MessageExceptionHandler;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author luowenjie
 * @since 2021/11/26 16:02
 */
@Slf4j
@Controller
public class WebSocketController {

    //通过SimpMessagingTemplate向用户发送消息
    @Autowired
    private SimpMessagingTemplate messagingTemplate;


    /**
     * 发送消息
     *@MessageMapping是stomp提供发送消息的注解，类似@RequestMappeing
     * @param json json文本
     */
    @MessageMapping("/sendChatMsg")
    @AutoLog(interceptor = MyAutoLogInterceptor.class, description = "ws.cmd")
    public void sendChatMsg( String json)throws Exception{
        if (StringUtils.isNotBlank(json) ) {
            //json转换为实体，JsonUtils代码不给了，自己到网上拿一个
            MsgWeixin po = JSONObject.parseObject(json, MsgWeixin.class);
            /*浏览器用户通讯订阅的地址.拼接聊天对话id，准确将消息发到某一个聊天中
             *防止一个对话能接收多个联系人的消息
             */
            String chatAddress = "/queue/contactMessage" + po.getChatId();
            //保存到数据库
            //msgWeixinService.insert();

            //若缓存已不存在accountId，证明是连接断开，不推送消息
            /*String cacheName = CacheConstant.WEBSOCKET_ACCOUNT;
            if (!CacheManager.containsKey(cacheName,cacheName+po.getToUserId()) ){
                return ;
            }*/
            //向用户发送消息,第一个参数是接收人、第二个参数是浏览器订阅的地址，第三个是消息本身
            messagingTemplate.convertAndSendToUser(po.getFromUserId(),chatAddress,po.getContent());
        }
    }

    //处理发送消息的错误,json是sendChatMsg方法的参数，传递到这里
    @MessageExceptionHandler
    public  void handleExceptions(Exception e,String json) {
        log.error("Error handling message: " + e.getMessage());
        MsgWeixin po = JSONObject.parseObject(json,MsgWeixin.class);
        //String errorJson = ResultUtil.getError(ResultCode.UN_KNOW_EXCEPTION);
        //把错误信息发回给发送人
        messagingTemplate.convertAndSendToUser( po.getFromUserId(),"/queue/contactErrors"+po.getChatId(),"");
    }

    @GetMapping("/loginSuccess")
    @ApiOperation(value = "跳转到登陆成功页面")
    public ModelAndView loginSuccess() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("loginSuccess");
        modelAndView.addObject("url", 12345);
        return modelAndView;
    }

}
